package com.sky.controller.user;

import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/user/addressBook")
@Api(tags = "地址簿接口")
public class AddressBookController {//自己写的day08

    @Autowired
    AddressBookService addressBookService;

    @PostMapping
    @ApiOperation("新增地址")
    public Result addAddressBook(@RequestBody AddressBook addressBook){
        log.info("新增地址：{}",addressBook);
        addressBookService.addAddressBook(addressBook);
        return Result.success();
    }

    @GetMapping("/list")
    @ApiOperation("查询当前用户所有地址")
    public Result<List<AddressBook>> listByUserId(){
        List<AddressBook> list = addressBookService.listByUserId();
        return Result.success(list);
    }

    @PutMapping("/default")
    @ApiOperation("设置默认地址")//注意：默认地址只能有一个,通过查询一开始默认地址，然后重置
    public Result setDefaultAddress(@RequestBody AddressBook addressBook){
        log.info("把id为{}设置为默认地址",addressBook.getId());
        addressBookService.setDefaultAddress(addressBook.getId());
        return Result.success();
    }

    @GetMapping("/default")
    @ApiOperation("查询默认地址")
    public Result<AddressBook> queryDefaultAddress(){
        AddressBook addressBook = addressBookService.queryDefaultAddress();
        return Result.success(addressBook);
    }

    @GetMapping("/{id}")
    @ApiOperation("根据ID查询地址,用于修改地址时的回显数据")
    public Result<AddressBook> queryAddressById(@PathVariable Long id){
        AddressBook addressBook = addressBookService.queryAddressById(id);
        return Result.success(addressBook);
    }

    @PutMapping
    @ApiOperation("修改地址")
    public Result updateAddressBook(@RequestBody AddressBook addressBook){
        log.info("修改地址的信息:{}",addressBook);
        addressBookService.updateAddressBook(addressBook);
        return Result.success();
    }

    @DeleteMapping
    @ApiOperation("删除地址")
    public Result deleteAddressBook(@RequestBody AddressBook addressBook){
        log.info("删除地址的信息：{}",addressBook);
        addressBookService.deleteAddressBook(addressBook.getId());
        return Result.success();

    }
}
